package com.app.couponsharelife.ui.main
import android.content.*
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import cn.jpush.android.api.JPushInterface
import com.alibaba.baichuan.android.trade.AlibcTradeSDK
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.gyf.barlibrary.ImmersionBar
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.SearchTBGoodsListBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.jpush.TagAliasOperatorHelper
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.ViewPagerAdapter
import com.app.couponsharelife.ui.dialog.SearchGoodsDialog
import com.app.couponsharelife.ui.dialog.SearchTextDialog
import com.app.couponsharelife.ui.dialog.TYGImagDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.HomeFragment
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.search.HomeSearchActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.main.me.NewMeFragment
import com.app.couponsharelife.ui.main.nativelife.NativeLifeActivity
import com.app.couponsharelife.ui.main.seeding.SeedingFragment
import com.app.couponsharelife.ui.main.sort.NewSortFragment
import com.app.couponsharelife.ui.main.sort.SortFragment
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.app.couponsharelife.utils.Logger
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.io.File
import java.io.FileNotFoundException
import java.lang.Exception
import java.util.concurrent.TimeUnit

class MainActivity : BaseActivity(), View.OnClickListener,TencentLocationListener{
    private var locationManager: TencentLocationManager? = null
    override val viewLayoutId: Int get() = R.layout.activity_main
    private var searchGoodsDialog:SearchGoodsDialog?=null
    private var mLastPosition = 0
    private var mAdapter: ViewPagerAdapter? = null
    private var mTitles = arrayListOf<String>()
    private var mPagers = arrayListOf<Fragment>()
    private var mClipboardManager: ClipboardManager?=null
    private var disposable: Disposable? = null
    private var indexType=""
    private var mOnPrimaryClipChangedListener: ClipboardManager.OnPrimaryClipChangedListener?=null
    private var exitTime:Long=0
    companion object {
        var isForeground = false
    }
    override fun initViews() {
        ImmersionBar.with(this).statusBarDarkFont(false).init()
        initViewPager()
        initNavigation()
        //registerClipEvents()
        initLocation()
        //registerMessageReceiver()
        disposeMessage(false,null)
        //registerReceiver(jPushMessageReceiver, IntentFilter())
        setAlias()
    }

    //ViewPager初始化
    private fun initViewPager() {
        /*ivTribeSelect.setOnClickListener {
            if (AppUtils.checkUserLogin()) {
                //mViewPager.setCurrentItem(2, false)
                startActivity(Intent(this, NativeLifeActivity::class.java))
            } else {
                //startActivity(Intent(this, LoginActivity::class.java))
                startActivity(Intent(this, NewLoginActivity::class.java))
            }
        }*/
        with(mTitles) {
            add("首页")
            add("分类")
            add("本地商圈")
            add("种草")
            add("我的")
        }
        with(mPagers) {
            add(HomeFragment.newInstance())
            //add(NewHomeFragment.newInstance())
            add(NewSortFragment.newInstance())
            //add(TribeFragment.newInstance())
            add(SortFragment.newInstance())
            //add(HeadLineFragment.newInstance())
            add(SeedingFragment.newInstance())
            //add(MeFragment.newInstance())
            add(NewMeFragment.newInstance())
        }
        mAdapter = ViewPagerAdapter(supportFragmentManager, mPagers, mTitles)
        mViewPager.offscreenPageLimit=5
        mViewPager.adapter = mAdapter
        mViewPager.setScroll(false)
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageSelected(position: Int) {
                resetNavigation()
                mLastPosition = position
                val view = mTabLayout.getTabAt(position)!!.customView
                val immersionBar= ImmersionBar.with(this@MainActivity)
                if (view != null) {
                    val textView = view.findViewById<TextView>(R.id.tvBotNavTitle)
                    when (mTabLayout.getTabAt(position)!!.position) {
                        0 -> {
                            RxBus.get().post("homefrg_fraeshbobo", "")
                            immersionBar.statusBarDarkFont(false).init()
                            textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                            view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_home_select)
                        }
                        1 -> {
                            hideWindow()
                            immersionBar.statusBarDarkFont(true).init()
                            textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                            view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_sort_select)
                        }
                        2 -> {
                            /*textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                            view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_tribe_select)*/
                        }
                        3 -> {
                            hideWindow()
                            immersionBar.statusBarDarkFont(true).init()
                            textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                            view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_headline_select)
                            if ("TribeFragment"==indexType){
                                val fragment=mPagers[position] as SeedingFragment
                                fragment.setPagerIndex(0)
                            }
                        }
                        4 -> {
                            hideWindow()
                            immersionBar.statusBarDarkFont(false).init()
                            textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                            view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_me_select)
                        }
                    }
                }
            }
        })
    }
    private fun hideWindow(){
        val fragment=mPagers[0]
        if (fragment!=null){
            (fragment as HomeFragment).hideSearchWindow()
        }
    }
    private fun resetNavigation() {
        val tab = mTabLayout.getTabAt(mLastPosition)
        if (tab != null) {
            val view = tab.customView
            if (view != null) {
                val textView = view.findViewById<TextView>(R.id.tvBotNavTitle)
                textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.gray_66))
                when (mLastPosition) {
                    0 -> view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_home_normal)
                    1 -> view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_sort_normal)
                    2 -> view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_tribe_normal)
                    3 -> view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_headline_normal)
                    4 -> view.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_me_normal)
                }
            }
        }
    }

    private fun initNavigation() {
        val width = AppUtils.getDisplayMetrics(this).widthPixels / 5
        for (i in 0..4) {
            val view = LayoutInflater.from(this).inflate(R.layout.home_bot_nav_item, null, false)
            view.layoutParams = LinearLayout.LayoutParams(width, AppUtils.dip2px(this, 49f))
            val imageView = view.findViewById<ImageView>(R.id.ivBotNavPic)
            val textView = view.findViewById<TextView>(R.id.tvBotNavTitle)
            textView.text = mTitles[i]
            textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.act_main_bot_nav_normal_text_color))
            when (i) {
                0 -> {
                    textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.red_f90))
                    imageView.setBackgroundResource(R.drawable.ic_bot_nav_home_select)
                }
                1 -> imageView.setBackgroundResource(R.drawable.ic_bot_nav_sort_normal)
                2 -> imageView.findViewById<View>(R.id.ivBotNavPic).setBackgroundResource(R.drawable.ic_bot_nav_tribe_normal)
                3 -> imageView.setBackgroundResource(R.drawable.ic_bot_nav_headline_normal)
                4 -> imageView.setBackgroundResource(R.drawable.ic_bot_nav_me_normal)
            }
            view.tag = i
            val newTab = mTabLayout.newTab()
            newTab.customView = view
            newTab.customView!!.setOnClickListener(this)
            mTabLayout.addTab(newTab)
        }
    }

    override fun onClick(view: View) {
        when (view.tag) {
            0 -> {
                mViewPager.setCurrentItem(0, false)
            }
            1 -> {
                mViewPager.setCurrentItem(1, false)
            }
            2 -> {
                if (AppUtils.checkUserLogin()) {
                    //mViewPager.setCurrentItem(2, false)
                    startActivity(Intent(this, NativeLifeActivity::class.java))
                } else {
                    //startActivity(Intent(this, LoginActivity::class.java))
                    startActivity(Intent(this, NewLoginActivity::class.java))
                }
            }
            3 -> {
                mViewPager.setCurrentItem(3, false)
            }
            4 -> {
                if (AppUtils.checkUserLogin()) {
                    mViewPager.setCurrentItem(4, false)
                } else {
                    //startActivity(Intent(this, LoginActivity::class.java))
                    startActivity(Intent(this, NewLoginActivity::class.java))
                }
            }
        }
    }

    fun scrollToPage(index: Int) {
        if (index < mPagers.size)
            mViewPager.setCurrentItem(index, false)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val bundle=intent?.extras
        val type=intent!!.getStringExtra("Type")?:""
        val status=intent!!.getStringExtra("Status")?:""
        indexType=type
        if ("ExperienceMen"==type){
            RxBus.get().post("mefrg_fraeshdata", "")
            setTYGDialog(status)
        }else if("TribeFragment"==type){
            mViewPager.setCurrentItem(3,false)
        }
        disposeMessage(true,bundle)
    }

    override fun onResume() {
        isForeground = true
        super.onResume()
    }

    /*override fun onPause() {
        isForeground = false
        super.onPause()
    }*/
    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) run {
            showToastMsg("再按一次退出")
            exitTime = System.currentTimeMillis()
        }else {
            super.onBackPressed()
        }
    }
    override fun onDestroy() {
        isForeground = false
        AlibcTradeSDK.destory()
        super.onDestroy()
        ImmersionBar.with(this).destroy()
        //unregisterReceiver(jPushMessageReceiver)
        disposable?.dispose()
        disposable==null
        if (mClipboardManager != null && mOnPrimaryClipChangedListener != null) {
            mClipboardManager!!.removePrimaryClipChangedListener(mOnPrimaryClipChangedListener)
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("savePic"))])
    fun savePic(images: ArrayList<String>) {
        showProgressDialog("请稍候")
        // 其次把文件插入到系统图库
        try {
            var count = 0
            for (item in images) {
                Glide.with(this).load(item)
                        .downloadOnly(object : SimpleTarget<File>() {
                            override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                                MediaStore.Images.Media.insertImage(contentResolver, resource.absolutePath, resource.name, null)
                                // 最后通知图库更新
                                sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(resource.absolutePath)))
                                count++
                                if (count == images.size) {
                                    dismissProgressDialog()
                                    showToastMsg("图片已保存")
                                }
                            }
                        })
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            dismissProgressDialog()
            showToastMsg("图片保存失败")
        }
    }
    private fun setTextDialog(content:String){
        SearchTextDialog(this,R.style.DialogStyle,content, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                val searchType=if (0==arg1){
                    "TB"
                }else{
                    "PDD"
                }
                val intent=Intent(this@MainActivity, HomeSearchActivity::class.java)
                intent.putExtra("KeyWord",content)
                intent.putExtra("SearchType",searchType)
                startActivity(intent)
            }
        }).show()
    }
    private fun setGoodsDialog(content:String,taobaoGoodBean: TaobaoGoodBean){
        if (searchGoodsDialog!=null&&searchGoodsDialog!!.isShowing){
            searchGoodsDialog!!.dismiss()
        }
        searchGoodsDialog = SearchGoodsDialog(this, R.style.DialogStyle, taobaoGoodBean, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                /*val intent = Intent(this@MainActivity, HomeSearchActivity::class.java)
                intent.putExtra("KeyWord", content)
                intent.putExtra("SearchType", "TB")
                startActivity(intent)*/
                val intent = Intent(this@MainActivity, GoodDetailActivity::class.java)
                intent.putExtra("good", taobaoGoodBean)
                startActivity(intent)
            }
        })
        searchGoodsDialog!!.show()
    }
    private fun setTYGDialog(type:String){
        TYGImagDialog(this,R.style.DialogStyle,object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                copyInviteCode("https://mp.yiyepay.cn/jkpaymp")
                showToastMsg("复制成功！")
            }
        },type).show()
        AppUtils.setString("SXPay","")
    }
    private fun registerClipEvents(){
        if (disposable==null) {
            disposable = Observable
                    .just("main")
                    .delay(3,TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe() {
                        mClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                        mOnPrimaryClipChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
                            if (mClipboardManager!!.hasPrimaryClip() &&mClipboardManager!!.primaryClip!=null&& mClipboardManager!!.primaryClip.itemCount > 0) {
                                // 获取复制、剪切的文本内容
                                val content = mClipboardManager!!.primaryClip.getItemAt(0).text.toString()
                                if (content.isNotEmpty()&&mLastPosition==0) {
                                    //setTextDialog(content)
                                    getGoodsList(content)
                                }
                            } else {

                            }
                        }
                        if (mClipboardManager!!.primaryClip!=null) {
                            val content = mClipboardManager!!.primaryClip.getItemAt(0).text.toString()
                            if (content.isNotEmpty()) {
                                //setTextDialog(content)
                                getGoodsList(content)
                                copyInviteCode("")
                            }
                            mClipboardManager!!.addPrimaryClipChangedListener(mOnPrimaryClipChangedListener)
                            disposable?.dispose()
                            disposable == null
                        }
                    }
        }
    }
    private fun copyInviteCode(code: String) {
        //获取剪贴板管理器：
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", code)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
    }
    private fun getGoodsList(keyword:String){
        val map=HashMap<String,String>()
        map["pageNo"]="1"
        map["pageSize"]="10"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["keyword"]=keyword
        RetrofitWorker.retrofitWorker.getTBGoodsList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoSearchData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<SearchTBGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<SearchTBGoodsListBean>) {
                        if (it.data!=null&&it.data!!.recordss.isNotEmpty()){
                            val taobaoGoodBean=it.data!!.recordss[0]
                            setGoodsDialog(keyword,taobaoGoodBean)
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            //Log.e("eee","---->"+e.toString())
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun initLocation() {
        val request = TencentLocationRequest.create()
        request.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
        locationManager = TencentLocationManager.getInstance(this)
        val error = locationManager?.requestLocationUpdates(request, this)
        /*if (error != 0) {
            locationManager?.removeUpdates(this@NativeLifeFragment)
            println("注册失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            AppUtils.setString("CityName", "杭州市")
            nativelifefrag_toolbar.title="杭州市"
        }*/
        /*Observable.create<Int> {
            val request = TencentLocationRequest.create()
            request.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
            locationManager = TencentLocationManager.getInstance(context)
            val error = locationManager?.requestLocationUpdates(request, this)
            it.onNext(error!!)
        }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object :DisposableObserver<Int>(){
            override fun onComplete() {

            }

            override fun onNext(error: Int) {
                if (error != 0) {
                    locationManager?.removeUpdates(this@NativeLifeFragment)
                    println("注册失败 $error")
                    AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
                    AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
                    AppUtils.setString("CityName", "杭州市")
                    nativelifefrag_toolbar.title="杭州市"
                }
            }

            override fun onError(e: Throwable) {
                Log.e("eee","---->${e.toString()}")
            }
        })*/
    }
    override fun onStatusUpdate(name: String?, error: Int, desc: String?) {
        if (name == "wifi" && error == 5) {
            showToastMsg("请打开GPS定位")
        }
    }

    override fun onLocationChanged(location: TencentLocation?, error: Int, reason: String?) {
        if (TencentLocation.ERROR_OK == error && location != null) {
            println(location)
            /*if (location.city.contains("金华")||location.city.contains("义乌")) {
                println("定位在 义乌")
                AppUtils.setString("Longitude", location.longitude.toString())
                AppUtils.setString("Latitude", location.latitude.toString())
            } else {
                println("定位不在 义乌")
                AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
                AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            }*/
            AppUtils.setString("Longitude", location.longitude.toString())
            AppUtils.setString("Latitude", location.latitude.toString())
            AppUtils.setString("CityName", location.city)
        } else {
            println("定位失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            AppUtils.setString("CityName", "杭州市")
        }
        //Log.e("eeee","---->定位结束")
        locationManager?.removeUpdates(this)
    }
    private fun disposeMessage(isOpen:Boolean,bundle:Bundle?){
        var type=""
        var link=""
        if (isOpen){
            if (bundle!=null){
                val extras = bundle.getString(JPushInterface.EXTRA_EXTRA)?:""
                if (extras.isNotEmpty()){
                    try {
                        val json=JSONObject(extras)
                        type=json.opt("type") as String
                        link=json.opt("datas") as String
                        //Log.e("eeee","app开着------>$type---->$link")
                    }catch (e: Exception){

                    }
                }
            }
        }else{
            type=intent.getStringExtra("type")?:""
            link=intent.getStringExtra("datas")?:""
            //Log.e("eeee","app关闭着------>$type---->$link")
        }
        if(type.isNotEmpty()&&link.isNotEmpty()) {
            //Log.e("eeee","Main---->$type---->$link")
            when (type) {
                "Goods" -> {
                    val goodBean = TaobaoGoodBean()
                    goodBean.item_id = link
                    goodBean.volume = "0"
                    goodBean.goodsSource1 = "好单库"
                    goodBean.small_images = ""
                    goodBean.pict_url = ""
                    val intent = Intent(this, GoodDetailActivity::class.java)
                    intent.putExtra("good", goodBean)
                    startActivity(intent)
                }
                "H5" -> {
                    val intent = Intent(this, ShopWebActivity::class.java)
                    intent.putExtra("url", link)
                    intent.putExtra("name", "")
                    startActivity(intent)
                }
                "Message" -> {

                }
                else -> {

                }
            }
        }
    }
    private fun setAlias() {
        val isSet=AppUtils.getString(Contacts.JPUSH_ALIAS,"false") //别名是否已经设置
        if ("false"==isSet){
            val alias = AppUtils.getString(Contacts.USERID, "")//别名
            Logger.e("mainactivity",  "设置别名")
            if ( alias.isNotEmpty()) {
                //设置别名或标签
                val tagAliasBean = TagAliasOperatorHelper.TagAliasBean()
                tagAliasBean.alias=alias
                tagAliasBean.action =TagAliasOperatorHelper().ACTION_SET
                tagAliasBean.isAliasAction =true
                TagAliasOperatorHelper().getInstance()?.handleAction(applicationContext, 1, tagAliasBean)
            }
        }else{
            Logger.e("mainactivity: ",  "别名已经设置---->$isSet")
        }
    }
}
